package com.wlf.admin.module.task;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlf.admin.common.dto.Const;
import com.wlf.admin.common.quartz.base.BaseQuartz;
import com.wlf.admin.system.domain.ScheduleJob;
import com.wlf.admin.system.domain.ScheduleLog;
import com.wlf.admin.system.service.ScheduleJobService;
import com.wlf.admin.system.service.ScheduleLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * 清理定时任务执行日志
 */
@Slf4j
@Component(Const.TaskBeanKey + "cleanTaskLogTask")
public class CleanTaskLogTask implements BaseQuartz {
    @Resource
    private ScheduleJobService scheduleJobService;
    @Resource
    private ScheduleLogService scheduleLogService;

    /**
     * 任务实现
     */
    @Override
    public void run(String params) {
        for (ScheduleJob scheduleJob : scheduleJobService.list()) {
            Long count = scheduleLogService.lambdaQuery()
                    .eq(ScheduleLog::getJobId, scheduleJob.getId())
                    .count();
            if (count > 1000) {
                // 分页获取根据时间排序的一千条数据
                Page<ScheduleLog> page = scheduleLogService.lambdaQuery()
                        .eq(ScheduleLog::getJobId, scheduleJob.getId())
                        .orderByDesc(ScheduleLog::getCreateTime)
                        .page(Page.of(1000L, 1000L));

                // 然后再删除
                scheduleLogService.removeBatchByIds(
                        page.getRecords().stream().map(ScheduleLog::getId)
                                .collect(Collectors.toList())
                );
            }
        }
    }
}
